package yxy.game.pm2.command.wuchao;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.wuchaogtopic;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.CurrencyHandle;
import yxy.game.pm2.module.wuchao.WuchaoModule;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent;
import yxy.game.pm2.module.wuchao.event.WuchaoEvent.EventType;

/** 乌巢 乌巢事件答题 */
@MessageType(proto = Command.WuchaoEventQuiz, classtype = WuchaoMessage.WuchaoEventQuizRequest.class)
public class CMD_WuchaoEventQuiz extends Command<WuchaoMessage.WuchaoEventQuizRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoEventQuizRequest request) {
		String playerCode = messageSource.getTag();
		String eventCode = request.getCode();
		int answer = request.getAnswer();

		WuchaoMessage.WuchaoEventQuizResponse.Builder response = WuchaoMessage.WuchaoEventQuizResponse.newBuilder();

		WuchaoModule wuchaoModule = WuchaoModule.get(playerCode);
		if (wuchaoModule.getStage() <= 0) {
			send(messageSource, response, Result.WuchaoNotStart);// 没有开始挑战
			return;
		}
		try {
			if (wuchaoModule.tryLock()) {
				WuchaoEvent event = wuchaoModule.getEvents().get(eventCode);

				if (event == null || event.isOver()) {
					send(messageSource, response, Result.WuchaoEventOver);// 事件不可用
					return;
				}
				if (!(event.getEventType().equals(EventType.Quiz))) {
					send(messageSource, response, Result.ParamError);// 事件不可用
					return;
				}

				int dataId = ((yxy.game.pm2.module.wuchao.event.WuchaoEventQuiz) event).getDataId();
				wuchaogtopic data = DataCenter.getData(dataId, wuchaogtopic.class);

				response.setCode(event.getCode());
				response.setReveal(data.getAnswer());
				if (answer == data.getAnswer()) {
					// 答对了
					Currency reward = Currency.create(data.getRewardtype(), data.getRewardid(), data.getRewardnum());
					new CurrencyHandle().addCurrency(playerCode, CCReason.乌巢之战, reward);

					response.addReward(new CurrencyHandle().packItem(reward));
				}
				event.setOver(true);
				wuchaoModule.set();

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			wuchaoModule.unlock();
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoEventQuizResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}